<template>
	<view class="container">
		<!-- 地图组件 -->
		<map class="map" :latitude="latitude" :longitude="longitude" :markers="markers" :polyline="polyline"
			scale="16"></map>

		<!-- 顶部地址信息 -->
		<view class="address-bar">
			<view class="address-item">
				<view class="dot start"></view>
				<text class="address-text">{{startAddress}}</text>
			</view>
			<view class="address-item">
				<view class="dot end"></view>
				<text class="address-text">{{endAddress}}</text>
			</view>
		</view>

		<!-- 可拖拉的面板 -->
		<view class="draggable-panel" :style="{ height: panelHeight + 'px' }" @touchstart="handleTouchStart"
			@touchmove="handleTouchMove" @touchend="handleTouchEnd">
			<!-- 面板内容 -->
			<view class="panel-content">
				<!-- 拖动条 -->
				<view class="panel-handle"></view>

				<!-- 左侧导航栏和右侧内容区 -->
				<view class="content-wrapper">
					<!-- 左侧导航栏 -->
					<view class="sidebar-container">
						<van-sidebar :active-key="currentCategory" @change="onSidebarChange">
						  <van-sidebar-item 
						    v-for="(category, index) in carCategories" 
						    :key="index" 
						    :title="category.modelName" 
						    :name="index"
						  />
						</van-sidebar>
					</view>

					<!-- 右侧内容区 -->
					<scroll-view 
						class="content-area" 
						scroll-y 
						:scroll-with-animation="true" 
						:scroll-top="scrollTop" 
						id="content-scroll" 
						@scroll="onContentScroll"
						:style="{ height: contentHeight + 'px' }"
					>
						<view 
							v-for="(category, categoryIndex) in carCategories" 
							:key="categoryIndex"
							:id="'section-' + categoryIndex"
							class="section-block" 
							:data-index="categoryIndex"
						>
							<view class="section-title">{{ category.modelName }}</view>
							<view class="section-debug">Debug: Section ID = section-{{category.modelName}}</view>
							<view v-for="(car, index) in getCarsByCategory(category.modelName)" 
								:key="index" 
								class="car-item"
								:class="{ 'selected': selectedCars.includes(car.carStyleId) }" 
								@tap="selectCar(car.carStyleId)"
							>
								<image src='/static/car-model.png' class="car-icon" mode="aspectFit" />
								<view class="car-info">
									<text class="car-name">{{car.carName}}</text>
									<text class="car-desc">{{car.priceType}}</text>
								</view>
								<view class="car-price">
									<text class="price">¥{{car.money}}</text>

								</view>
								<view class="checkbox">
									<view class="checkbox-inner" :class="{ 'checked': selectedCars.includes(car.carStyleId) }">
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>

				<!-- 底部确认按钮 -->
				<view class="bottom-button">
					<view class="price-info" v-if="selectedCars.length > 0">
						<text class="total-price">¥{{maxPrice}}</text>
						<text class="price-desc">预估最高价</text>
					</view>
					<button class="confirm-btn" @tap="confirmSelection">确认选择</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '../../common/qqmap-wx-jssdk.js'
	import selectCarApi from '@/api/selectCar.js'
	export default {
		data() {
			return {
				latitude: 39.908823, // 默认纬度
				longitude: 116.397470, // 默认经度
				//终点：
				endLat : null,
				endLng: null,
				startAddress: '当前位置',
				endAddress: '目的地',
				markers: [], // 地图标记点
				polyline: [], // 路线
				panelHeight: 400, // 初始面板高度
				startY: 0, // 开始拖动时的Y坐标
				startHeight: 0, // 开始拖动时的面板高度
				isDragging: false, // 是否正在拖动
				selectedCars: [], // 存储多个选中的车型索引
				currentCategory: 0,
				scrollTop: 0, // 控制滚动位置
				sectionPositions: [], // 存储各section的位置
				scrollTimer: null, // 滚动节流定时器
				qqmapsdk: '',
				carCategories: [],
				carTypes: [],
				kilometer:null,//距离
				isManualScrolling: false, // 添加标记来区分手动滚动和自动滚动
			}
		},
		computed: {
			//计算最后的价格，一选择的车型中最高的价格为主
			maxPrice() {
				if (this.selectedCars.length === 0) return 0;
				return Math.max(...this.selectedCars.map(id => {
					const car = this.carTypes.find(car => car.carStyleId === id);
					return car ? car.money : 0;
				}));
			},
			
			// 计算内容区域高度
			contentHeight() {
				// 面板高度减去拖动条和底部按钮的高度
				// 底部按钮占据约100px(含padding)
				return this.panelHeight - 120;
			}
		},
		onLoad(options) {
			// 获取页面传递的起终点坐标
			if (options.startLat && options.startLng && options.endLat && options.endLng) {
				this.latitude = parseFloat(options.startLat);
				this.longitude = parseFloat(options.startLng);
				this.endLat = parseFloat(options.endLat)
				this.endLng = parseFloat(options.endLng);
				const endLat = parseFloat(options.endLat);
				const endLng = parseFloat(options.endLng);

				// 设置起终点标记
				this.markers = [{
						id: 1,
						latitude: this.latitude,
						longitude: this.longitude,
						iconPath: '../../static/now.png',
						width: 32,
						height: 32
					},
					{
						id: 2,
						latitude: endLat,
						longitude: endLng,
						iconPath: '../../static/destination.png',
						width: 32,
						height: 32
					}
				];
				//使用定位api
				this.qqmapsdk = new QQMapWX({
					key: 'XQ5BZ-2WYW3-UPH3H-RXWXX-B5DRK-6CBJG'
				});
				// console.log(this.latitude);
				//启用路线规划
				this.qqmapsdk.direction({
					mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
					//from参数不填默认当前地址
					from: `${this.latitude},${this.longitude}`,
					to: `${endLat},${endLng}`,
					success: (res) => {
						// console.log(res);
						const ret = res;
						const coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						const kr = 1000000;
						for (let i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						}
						//将解压后的坐标放入点串数组pl中
						for (let i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						}
						// console.log(pl);
						// 更新路线数据
						this.polyline = [{
							points: pl,
							color: '#009a00dd',
							width: 10
						}];
					},
					fail: function(error) {
						// console.error(error);
					},
					complete: function(res) {
						// console.log(res);
					}
				});
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: endLat,
						longitude: endLng
					},
					success: (res) => {
						// console.log('Reverse geocoding result:', res);
						let {
							address,
							ad_info
						} = res.result;
						this.address = ad_info.city ? ad_info.city : '定位失败';
						this.endAddress = res.result.formatted_addresses.recommend;
						// console.log('Address:', this.address);
					},
					fail: (err) => {
						// console.error('Reverse geocoding failed:', err);
					}
				});
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: this.latitude,
						longitude: this.longitude
					},
					success: (res) => {
						// console.log('Reverse geocoding result:', res);
						let {
							address,
							ad_info
						} = res.result;
						this.address = ad_info.city ? ad_info.city : '定位失败';
						this.startAddress = res.result.formatted_addresses.recommend;
						// console.log('Address:', this.address);
					},
					fail: (err) => {
						// console.error('Reverse geocoding failed:', err);
					}
				});
				//计算距离
				this.kilometer = this.getMapDistance(this.latitude,this.longitude,endLat,endLng)
				
			}
		},
		mounted() {
			// 页面加载完成后，获取并存储每个section的位置
			setTimeout(() => {
				this.calculateSectionPositions();
			}, 500);
			this.getCarType();
			this.getCar();
		},
		methods: {
			//后端得到车的类型
			getCarType(){
				selectCarApi.getCarType().then(res=>{
					// console.log(res,"----432");
					this.carCategories = res
				}).catch(err => {
					// console.log('获取失败:', err);
					uni.showToast({
						title: '获取失败',
						icon: 'none'
					});
				}).finally(() => {
					// 延迟重置状态，防止快速点击
					setTimeout(() => {
						this.isRefreshing = false;
					}, 1000);
				});
			},
			//后端得到对应的车型
			getCar(){
				// const kilometer = 3.7
				selectCarApi.getCar(this.kilometer).then(res=>{
					console.log(res,"4352545555235245");
					this.carTypes = res;
				}).catch(err => {
					// console.log('获取失败:', err);
					uni.showToast({
						title: '获取失败',
						icon: 'none'
					});
				}).finally(() => {
					// 延迟重置状态，防止快速点击
					setTimeout(() => {
						this.isRefreshing = false;
					}, 1000);
				});
			},
			//生成订单
			createOrder(tripOrder){
				// uni.navigateTo({
				// 	url: `/pages/placeOrder/placeOrder?data=` + encodeURIComponent(JSON.stringify(tripOrder))
				// });
				selectCarApi.insertOrder(tripOrder).then(res =>{
					// console.log(tripOrder);
					console.log(res);
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/placeOrder/placeOrder?orderId=' + encodeURIComponent(res)
						});
					}, 500);	
				}).catch(err => {
					console.log('获取失败:', err);
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
				}).finally(() => {
					// 延迟重置状态，防止快速点击
					setTimeout(() => {
						this.isRefreshing = false;
					}, 1000);
				});
			},
			// 计算并存储各个滚动分类的位置
			calculateSectionPositions() {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.section-block').boundingClientRect(rects => {
					if (!rects || !rects.length) return;
					
					this.sectionPositions = rects.map(rect => {
						return {
							id: rect.id,
							top: rect.top,
							height: rect.height
						};
					});
					// console.log('获取到section位置:', this.sectionPositions);
				}).exec();
			},
			// 处理触摸开始
			handleTouchStart(e) {
				this.startY = e.touches[0].pageY;
				this.startHeight = this.panelHeight;
				this.isDragging = true;
			},

			// 处理触摸移动
			handleTouchMove(e) {
				if (!this.isDragging) return;

				const currentY = e.touches[0].pageY;
				const deltaY = currentY - this.startY;

				// 计算新的面板高度
				let newHeight = this.startHeight - deltaY;

				// 限制面板高度范围（200px 到 600px）
				newHeight = Math.max(200, Math.min(600, newHeight));

				this.panelHeight = newHeight;
			},

			// 处理触摸结束
			handleTouchEnd() {
				this.isDragging = false;
				// 拖拽结束后重新计算各section位置
				setTimeout(() => {
					this.calculateSectionPositions();
				}, 300);
			},
			//分组车的类型
			getCarsByCategory(modelName) {
				return this.carTypes.filter(car => car.modelName === modelName);
			},
			//查找滚动的分类目标位置
			scrollToSection(index) {
				// console.log('滚动到分类:', index);
				this.currentCategory = index;
				this.isManualScrolling = true;
				
				// 使用索引作为section ID
				const sectionId = `section-${index}`;
				
				// 使用uni.createSelectorQuery获取元素位置信息
				const query = uni.createSelectorQuery().in(this);
				
				// 获取scroll-view的位置信息
				query.select('.content-area').boundingClientRect();
				// 获取目标section的位置信息
				query.select(`#${sectionId}`).boundingClientRect();
				// 获取当前滚动位置
				query.select('.content-area').scrollOffset();
				
				query.exec(([scrollViewRect, sectionRect, scrollOffset]) => {
					if (!scrollViewRect || !sectionRect || !scrollOffset) return;
					
					// 计算相对于scroll-view的偏移量
					const relativeOffset = sectionRect.top - scrollViewRect.top;
					
					// 计算目标滚动位置
					const targetScrollTop = scrollOffset.scrollTop + relativeOffset;
		
					// 设置滚动位置
					this.scrollTop = targetScrollTop;
					
					// 500ms后重置手动滚动标记
					setTimeout(() => {
						this.isManualScrolling = false;
					}, 500);
				});
			},
			// 监听内容区域滚动
			onContentScroll(e) {
				if (this.isManualScrolling) return;
				
				const scrollTop = e.detail.scrollTop;
				
				// 使用节流函数减少查询次数
				if (this.scrollTimer) clearTimeout(this.scrollTimer);
				this.scrollTimer = setTimeout(() => {
					// 获取所有section的位置
					const query = uni.createSelectorQuery().in(this);
					query.selectAll('.section-block').boundingClientRect(rects => {
						if (!rects) return;
						
						// 找到当前可见的section
						let currentIndex = 0;
						for (let i = 0; i < rects.length; i++) {
							if (rects[i].top >= 0) {
								currentIndex = i;
								break;
							}
						}
						
						// 更新当前分类
						if (this.currentCategory !== currentIndex) {
							this.currentCategory = currentIndex;
						}
					}).exec();
				}, 100);
			},
			//改变导航的定位
			onSidebarChange(event) {
				const index = event.detail;
				// console.log(index,121132)
				this.currentCategory = index;
				// console.log(this.currentCategory,121132)
				this.scrollToSection(index);
			},
			//选择的车型id
			selectCar(id) {
				const carIndex = this.selectedCars.indexOf(id);
				if (carIndex === -1) {
					this.selectedCars.push(id);
				} else {
					this.selectedCars.splice(carIndex, 1);
				}
			},
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			
			/*
			 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
			 默认单位km
			*/
			getMapDistance(lat1, lng1, lat2, lng2) {
				// console.log("in getMap")
				// console.log(lat1)
				var radLat1 = this.Rad(lat1);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(lng1) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000; //输出为公里
				//s=s.toFixed(2);
				console.log(s,11111111111111111111111111111);
				return s;
			},
			// 确认选择车型按钮-生成订单
			confirmSelection() {
				if (this.selectedCars.length === 0) {
					uni.showToast({
						title: '请选择车型',
						icon: 'none'
					});
					return;
				}
				// 获取选中的车型信息
				const selectedCarsInfo = this.selectedCars.map(id => this.carTypes.find(car => car.carStyleId === id));
				// console.log('选中的车型：', selectedCarsInfo);
				const selectedCarIds = selectedCarsInfo.map(car => car.carStyleId);
				const selectedCarsWithMoney = selectedCarsInfo.reduce((acc, car) => {
				  acc[car.carStyleId] = car.money; // 动态添加键值对
				  return acc;
				}, {}); // 初始值为空对象 {}
				// console.log('选中的车型及其价格：', selectedCarsWithMoney);
				// console.log('选中的车型ID：', selectedCarIds);
			
				uni.showToast({
					title: `已选择${this.selectedCars.length}种车型`,
					icon: 'success'
				});
				//拿到用户数据
				const userData = uni.getStorageSync('user');
				const startLat = this.latitude*1000000;
				const startLng = this.longitude*1000000;
				const endLat = this.endLat*1000000;
				const endLng = this.endLng*1000000;
				// console.log(startLat,startLng,endLat,endLng,23131)
				const tripOrder = {
					passengerId : userData.userId,
					startAddress:this.startAddress,
					startLat:startLat,
					startLng:startLng,
					endAddress:this.endAddress,
					endLat:endLat,
					endLng:endLng,
					carType:selectedCarIds,
					carPrice:selectedCarsWithMoney
				}
				// console.log(tripOrder);
				this.createOrder(tripOrder)
					
			}
		}
	}
</script>

<style>
	.container {
		position: relative;
		width: 100vw;
		height: 100vh;
	}

	.map {
		width: 100%;
		height: 100%;
	}

	.address-bar {
		position: absolute;
		top: 40rpx;
		left: 40rpx;
		right: 40rpx;
		background-color: rgba(255, 255, 255, 0.8);
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.address-item {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
	}

	.dot {
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.dot.start {
		background-color: #007AFF;
	}

	.dot.end {
		background-color: #FF3B30;
	}

	.address-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.draggable-panel {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		transition: height 0.3s ease;
	}

	.panel-content {
		padding: 20rpx;
	}

	.panel-handle {
		width: 60rpx;
		height: 6rpx;
		background-color: #ddd;
		border-radius: 3rpx;
		margin: 0 auto 30rpx;
	}

	.content-wrapper {
		display: flex;
		height: calc(100% - 180rpx);
		position: relative;
		padding-bottom: 130rpx; /* 为底部按钮预留空间 */
	}

	.sidebar-container {
		width: 160rpx;
		height: 100%;
		background-color: #f8f8f8;
		border-right: 1rpx solid #eee;
	}
	
	/* vant样式覆盖 */
	.van-sidebar {
		width: 160rpx !important;
	}

	.van-sidebar-item {
		padding: 20rpx 12rpx !important;
		text-align: center !important;
		font-size: 28rpx !important;
	}

	.van-sidebar-item--selected {
		color: #007AFF !important;
		font-weight: bold !important;
		border-color: #007AFF !important;
	}

	.content-area {
		flex: 1;
		background-color: #fff;
		padding: 0 20rpx;
		height: 100%;
		overflow-y: scroll;
		-webkit-overflow-scrolling: touch;
		position: relative;
	}

	.section-block {
		margin-bottom: 40rpx;
		padding-bottom: 20rpx;
		position: relative;
	}

	.section-title {
		padding: 30rpx 20rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		background-color: #f8f8f8;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 20rpx;
	}

	.car-list {
		padding: 0;
	}

	.car-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.car-item.selected {
		background-color: #f0f9ff;
	}

	.car-icon {
		width: 100rpx;
		height: 100rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.car-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding-right: 20rpx;
	}

	.car-name {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 8rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.car-desc {
		font-size: 24rpx;
		color: #666;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.car-price {
		text-align: right;
		margin: 0 30rpx;
		flex-shrink: 0;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.price {
		font-size: 36rpx;
		color: #ff6b6b;
		font-weight: bold;
		line-height: 1;
	}

	.unit {
		font-size: 24rpx;
		color: #999;
		margin-top: 4rpx;
	}

	.checkbox {
		width: 48rpx;
		height: 48rpx;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.checkbox-inner {
		width: 32rpx;
		height: 32rpx;
		border-radius: 4rpx;
		background-color: transparent;
		transition: background-color 0.3s;
	}

	.checkbox-inner.checked {
		background-color: #007AFF;
	}

	.bottom-button {
		padding: 30rpx 20rpx;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-top: 1rpx solid #eee;
		z-index: 10;
	}

	.price-info {
		display: flex;
		flex-direction: column;
	}

	.total-price {
		font-size: 40rpx;
		color: #ff6b6b;
		font-weight: bold;
	}

	.price-desc {
		font-size: 24rpx;
		color: #999;
	}

	.confirm-btn {
		width: 240rpx;
		height: 88rpx;
		line-height: 88rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		text-align: center;
	}

	.confirm-btn:active {
		opacity: 0.8;
	}

	.section-debug {
		font-size: 12px;
		color: #999;
		padding: 4px;
		display: none; /* 默认隐藏，需要时可以改为 block */
	}
</style>